//
//  MOLockViewController.m
//  WCImApp
//
//  Created by Hyukooooh on 2024/4/7.
//  Copyright © 2024 WCImApp. All rights reserved.
//

#import "MOLockViewController.h"
#import "MPLockHelper.h"
#import "MONumberPassword.h"
#import "MOLocalAuthentication.h"
#import "CoreLockConst.h"
#import "CLLockView.h"
#import "CLLockInfoView.h"
#import "CLLockLabel.h"
//#import "QARtcEngine.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "IQKeyboardManager.h"
#import "QAAPI+Global.h"
#import "MOLockAlertVC.h"
#import <AFNetworking/AFHTTPSessionManager.h>
#import "QALastHeadImage.h"
#import "QABaseNavigationController.h"
@interface MOLockViewController ()

/** 操作成功：密码设置成功、密码验证成功 */
@property (nonatomic,copy) void (^successBlock)(MOLockViewController *lockVC,NSString *pwd);
@property (nonatomic,copy) void (^forgetPwdBlock)(void);
@property (nonatomic,copy) void (^closeBlock)(void);

@property (nonatomic, strong) CLLockInfoView *lockInfoView;
@property (nonatomic, strong) CLLockView *lockView;
@property (nonatomic, strong) CLLockLabel *nameLb;

@property (nonatomic,weak) UIViewController *vc;

@property (nonatomic, strong) UIView *topContainerView;
@property (nonatomic, strong) UIImageView *userHeader;
@property (nonatomic, strong) UIView *userHeaderShadowView;

@property (nonatomic, strong) MONumberPassword *numberPasswordView;
@property (nonatomic, strong) UIButton *passwordStyleButton;
@property (nonatomic, strong) UIButton *useGestureBtn;
@property (nonatomic,strong) UILabel *titleText;
@property (nonatomic,copy) NSString *msg;
@property (nonatomic,copy) NSString *modifyCurrentTitle;
/** 直接进入修改页面的 */
@property (nonatomic,assign) BOOL isDirectModify;
//应用锁类型 YES:数字类型 NO:手势类型
@property (nonatomic, assign) BOOL psdStyle;
@property (nonatomic, strong) UIButton *closeBtn;
//错误前的提示文案
@property (nonatomic, copy) NSString *beforeErrorText;

//注册设置
//设置应用锁，让你的账号更安全
@property (nonatomic, strong) UILabel *firstSubLabel;

/** window */
@property (nonatomic, strong) UIWindow            *lockWindow;
@property (nonatomic, strong) UIImageView *touchIDImgV;
@property (nonatomic, strong) UIImageView *faceIDImgV;
@property (nonatomic, strong) UILabel *errorTimesLb;
@property (nonatomic, assign) BOOL shouldAutoCallFace;
@property (nonatomic, strong) MOAlerter *networkAlerter;

@property (nonatomic, strong) MOAlerter *vipAlerter;
@property (nonatomic, strong) MOAlerter *infoChangedAlerter;

@property (strong, nonatomic) AFHTTPSessionManager *sessionManager;
@end

static BOOL _isLocking;
@implementation MOLockViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SuspensionEntranceHidden" object:@(NO)];
    [_sessionManager.reachabilityManager stopMonitoring];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 60;
    [IQKeyboardManager sharedManager].shouldToolbarUsesTextFieldTintColor = NO;
    [IQKeyboardManager sharedManager].toolbarTintColor = main_blue_color;
    if (self.hideLeftNavBtn) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:(UIBarButtonItemStylePlain) target:nil action:nil];
    }
}

- (BOOL)_hasSetAutoUnregister{
    return [MPLockHelper getUnregisterCount] > 0;
}

- (void)appDidBecomeActive{
    BOOL hasOpenIDPassword = [MPLockHelper hasOpenIDPassword];
    if(!hasOpenIDPassword){
        return;
    }
    __weak typeof (self) weakSelf = self;
    
    [MOLocalAuthentication evaluatedPolicyDomainStateChangedComplete:^(BOOL changed, BOOL shouldAlert) {
        if(changed){
            [weakSelf hiddenAllAuthenticationFeature];
        }
        //1、在安全中开启面容ID开关2、挂后台，在系统设置中清除面容3、重新打开app 需要给出提示
        if(shouldAlert){
            if(!weakSelf.infoChangedAlerter){
                weakSelf.infoChangedAlerter = [MOAlerter alertWithTitle:@"提示" message:[MOLocalAuthentication domainStateChangedNotice] leftTitle:nil leftAction:nil rightTitle:@"我知道了" rightAction:^(MOAlerter *alerter) {
                    weakSelf.infoChangedAlerter = nil;
                } touchHide:NO superView:weakSelf.view];
            }
        }
    }];
    
    [MOLocalAuthentication judgeBiometricsStatusComplete:^(BOOL availabel) {
        if(!availabel){
            [weakSelf hiddenAllAuthenticationFeature];
        }
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (self.hideLeftNavBtn) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:(UIBarButtonItemStylePlain) target:nil action:nil];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
    [[IQKeyboardManager sharedManager] setEnable:NO];
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 10;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([self _hasSetAutoUnregister]){
        //检测网络状态  如果没网络加一个强弹窗
        _sessionManager = [AFHTTPSessionManager manager];
        [_sessionManager.reachabilityManager startMonitoring];
        __weak typeof(self)weakSelf = self;
        [_sessionManager.reachabilityManager setReachabilityStatusChangeBlock:^void(AFNetworkReachabilityStatus status) {
            if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {
                if(weakSelf.networkAlerter){
                    [weakSelf.networkAlerter hide];
                    weakSelf.networkAlerter = nil;
                }
            } else {
                if(!weakSelf.networkAlerter){
                    weakSelf.networkAlerter = [MOAlerter alertWithTitle:nil message:@"当前网络不可用，请检查您的网络设置" leftTitle:nil leftAction:nil rightTitle:@"去设置" rightAction:^(MOAlerter *alerter) {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                    } touchHide:NO superView:weakSelf.view clickNoHide:YES];
                }
            }
        }];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    [self layoutUI];
    [self vcPrepare];
    //数据传输
    [self dataTransfer];
    //手势密码事件
    [self gesturePasswordEvent];
    //数字密码事件
    [self numberPasswordEvent];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SuspensionEntranceHidden" object:@(YES)];
    //判断已经错误的次数，如果达到上限，递归调用注销接口
    NSInteger times = [CoreArchive intForKey:ERROR_TIMES];
    NSInteger unregisterCount = [MPLockHelper getUnregisterCount];
    if(unregisterCount > 0 && times >= [MPLockHelper getUnregisterCount]){
        [self _callCancelAccount];
    }
    __weak typeof (self) weakSelf = self;
    
    //如果可以自动唤起人脸识别 最后再判断一下用户是否有将设备功能关闭
    if(self.shouldAutoCallFace){
        [MOLocalAuthentication judgeBiometricsStatusComplete:^(BOOL availabel) {
            if(availabel){
                //自动唤起面容识别
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf faceIDTap];
                });
            }else{
                //如果此时不可用，说明是用户开启面部解锁后，又去设备中移除面容，在这里移除面部解锁状态
                [weakSelf hiddenAllAuthenticationFeature];
            }
        }];
    }
   
}

/**
 *  数据传输
 */
- (void)dataTransfer {
    [self.nameLb showNormalMsg:self.msg];
    [self.numberPasswordView tipEditWithContent:self.msg isError:NO];
    //传递类型
    self.lockView.type = self.type;
    self.numberPasswordView.type = self.type;
}

- (void)vcPrepare{
    self.view.backgroundColor = [UIColor colorWithLightColorStr:@"FFFFFF" DarkColor:@"131C26"];
    self.numberPasswordView.backgroundColor = [UIColor colorWithLightColorStr:@"FFFFFF" DarkColor:@"131C26"];
    //初始情况隐藏
    self.navigationItem.rightBarButtonItem = nil;
    self.navigationView.backgroundColor = UIColor.clearColor;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@""
                                                                             style:UIBarButtonItemStylePlain
                                                                            target:nil
                                                                            action:nil];
    
    _userHeaderShadowView.hidden = YES;
    
    //默认标题
    if (_psdStyle) {
        //数字密码
        _numberPasswordView.hidden = NO;
        _numberPasswordView.isLocal = YES;
        _modifyCurrentTitle = CoreLockNumberModifyNormalTitle;
        _useGestureBtn.hidden = NO;
        _passwordStyleButton.hidden = YES;
        _lockView.hidden = YES;
        _lockInfoView.hidden = YES;
    }else{
        _numberPasswordView.hidden = YES;
        _modifyCurrentTitle = CoreLockModifyNormalTitle;
        _passwordStyleButton.hidden = NO;
        _lockView.hidden = NO;
        _lockInfoView.hidden = NO;
    }
    
    switch (_type) {
        case MOLockType_Set:
        {
            [self showCloseBarButtonItem];
        }
            break;
        case MOLockType_Verify:
        {
            _lockInfoView.hidden = YES;
            if (self.isClosePsd) {
                _userHeader.hidden = YES;
                _userHeaderShadowView.hidden = YES;
                self.numberPasswordView.headerBtn.hidden = YES;
                [self showCloseBarButtonItem];
            } else {
                _userHeader.hidden = NO;
                _userHeaderShadowView.hidden = NO;
                self.numberPasswordView.headerBtn.hidden = NO;
                NSURL *headerUrl = [NSURL URLWithString:WCICache.user.userIcon];
                [_userHeader sd_setImageWithURL:headerUrl placeholderImage:[QALastHeadImage getUserHeaderImage:WCICache.user.userId]];
                [self.numberPasswordView.headerBtn sd_setImageWithURL:headerUrl forState:UIControlStateNormal placeholderImage:[QALastHeadImage getUserHeaderImage:WCICache.user.userId]];
                BOOL hasOpenIDPassword = [MPLockHelper hasOpenIDPassword];
                MOLocalAuthenticationType type = [MOLocalAuthentication deviceSupportAuthType];
                if(hasOpenIDPassword){
                    if(type == MOLocalAuthenticationType_faceID){
                        _faceIDImgV.hidden = !hasOpenIDPassword;
                        _shouldAutoCallFace = hasOpenIDPassword;
                    }else{
                        _touchIDImgV.hidden = (!hasOpenIDPassword || _psdStyle);
                        _shouldAutoCallFace = hasOpenIDPassword;
                    }
                    //更新数字密码视图
                    if(_psdStyle){
                        if(type == MOLocalAuthenticationType_faceID){
                            [self.numberPasswordView updateConstraintsWhenLocalAuth];
                            [_lockView mas_updateConstraints:^(MASConstraintMaker *make) {
                                make.top.equalTo(_topContainerView.mas_bottom).offset(100);
                            }];
                            _shouldAutoCallFace = YES;
                        }else{
                            [_numberPasswordView touchIDHiddenState:NO];
                            _shouldAutoCallFace = YES;
                        }
                    }
                    __weak typeof (self) weakSelf = self;
                    
                    [MOLocalAuthentication evaluatedPolicyDomainStateChangedComplete:^(BOOL changed, BOOL shouldAlert) {
                        if(changed){
                            [weakSelf hiddenAllAuthenticationFeature];
                        }
                        //1、在安全中开启面容ID开关2、挂后台，在系统设置中清除面容3、重新打开app 需要给出提示
                        if(shouldAlert){
                            if(!weakSelf.infoChangedAlerter){
                                weakSelf.infoChangedAlerter = [MOAlerter alertWithTitle:@"提示" message:[MOLocalAuthentication domainStateChangedNotice] leftTitle:nil leftAction:nil rightTitle:@"我知道了" rightAction:^(MOAlerter *alerter) {
                                    weakSelf.infoChangedAlerter = nil;
                                } touchHide:NO superView:weakSelf.view];
                            }
                        }
                    }];
                }
                if(_psdStyle){
                    //数字
                    if(type == MOLocalAuthenticationType_faceID){
                        [_faceIDImgV mas_remakeConstraints:^(MASConstraintMaker *make) {
                            make.width.height.mas_equalTo(32);
                            make.centerX.equalTo(self.view);
                            make.top.equalTo(self.view).offset([_numberPasswordView tipLabMaxY] + 25);
                        }];
                        [_errorTimesLb mas_updateConstraints:^(MASConstraintMaker *make) {
                            make.top.equalTo(_faceIDImgV.mas_bottom).offset(5);
                        }];
                    }else{
                        [_errorTimesLb mas_remakeConstraints:^(MASConstraintMaker *make) {
                            make.centerX.equalTo(self.view);
                            make.top.equalTo(_numberPasswordView).offset(0.22*SCREEN_HEIGHT + WCI_IPHONE_STATUSBAR_HEIGHT + 9 + 5);
                        }];
                    }
                }else{
                    if(!hasOpenIDPassword){
                        //手势+未开启生物解锁
                        [_errorTimesLb mas_remakeConstraints:^(MASConstraintMaker *make) {
                            make.centerX.equalTo(self.view);
                            make.bottom.equalTo(_lockView.mas_top);
                        }];
                    }else{
                        //手势+开启生物解锁
                        if(type == MOLocalAuthenticationType_touchID){
                            [_lockView mas_updateConstraints:^(MASConstraintMaker *make) {
                                make.top.equalTo(_topContainerView.mas_bottom).offset(WCI_ScaleWidth(45));
                            }];
                            [_errorTimesLb mas_remakeConstraints:^(MASConstraintMaker *make) {
                                make.centerX.equalTo(self.view);
                                make.bottom.equalTo(_lockView.mas_top);
                            }];
                        }
                    }
                }
            }
            [self.passwordStyleButton setTitleColor:UIColorFromRGB(182, 183, 186) forState:UIControlStateNormal];
            [self.useGestureBtn setTitleColor:UIColorFromRGB(182, 183, 186) forState:UIControlStateNormal];
            [self.passwordStyleButton setTitle:@"忘记应用锁密码" forState:UIControlStateNormal];
            [self.useGestureBtn setTitle:@"忘记应用锁密码" forState:UIControlStateNormal];
        }
            break;
        case MOLockType_Modify:
        {
            _lockInfoView.hidden = YES;
            if (_isDirectModify) return;
            [self showCloseBarButtonItem];
            [self.passwordStyleButton setTitleColor:UIColorFromRGB(182, 183, 186) forState:UIControlStateNormal];
            [self.useGestureBtn setTitleColor:UIColorFromRGB(182, 183, 186) forState:UIControlStateNormal];
            [self.passwordStyleButton setTitle:@"忘记应用锁密码" forState:UIControlStateNormal];
            [self.useGestureBtn setTitle:@"忘记应用锁密码" forState:UIControlStateNormal];
        }
            break;
        case MOLockType_FirstSet:
        {
            self.navigationItem.title = @"设置应用锁";
            [self showJumpBarButtonItem];
            [self.view addSubview:self.firstSubLabel];
            _firstSubLabel.hidden = NO;
            [_firstSubLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(self.lockView.mas_top).offset(6);
                make.centerX.equalTo(self.view);
                make.left.offset(16);
                make.right.offset(-16);
            }];
        }
            break;
        default:
            break;
    }
}

#pragma mark -- private Method
- (void)hiddenAllAuthenticationFeature{
    [MPLockHelper openIDPassword:NO];
    [MPLockHelper resetUnregisterCount:0];
    _shouldAutoCallFace = NO;
    _faceIDImgV.hidden = YES;
    _touchIDImgV.hidden = YES;
    [_numberPasswordView touchIDHiddenState:YES];
}

- (void)_authFailIsNumberPassword:(BOOL)isNumberPassword{
    __weak typeof (self) weakSelf = self;
    //密码不一致
    NSInteger times = [CoreArchive intForKey:ERROR_TIMES];
    NSInteger showErrorTimes = 4 - times;
    [CoreArchive setInt:times + 1 key:ERROR_TIMES];
    
    if([self _hasSetAutoUnregister]){
        if(times + 1 >= [MPLockHelper getUnregisterCount]){
            self.errorTimesLb.hidden = YES;
            //倒计时5秒后退出登录、并注销账号
            [MOLockAlertVC presentAlertViewFromViewController:self content:@"" count:5 btnCallback:^(NSUInteger index) {
                [weakSelf _callCancelAccount];
            }];
            return;
        }
    }
    if (showErrorTimes == 0) {
        [MOAlerter alertWithTitle:@"应用锁已失效" message:@"请重新登录，并到安全中心设置应用锁" leftTitle:@"" leftAction:nil rightTitle:@"我知道了" rightAction:^(MOAlerter *alerter) {
            [weakSelf dismiss];
            if (weakSelf.forgetPwdBlock != nil) weakSelf.forgetPwdBlock();
        } touchHide:NO superView:weakSelf.alertSuperView];
        [self clearAboutPasswordLocalValue];
        [self clearLoginSuccessData];
    } else {
        if([self _hasSetAutoUnregister]){
            self.errorTimesLb.text = [NSString stringWithFormat:(@"密码已错%ld次,连续错误%ld次将自动注销吉信账号"),times + 1,[MPLockHelper getUnregisterCount]];
        }else{
            self.errorTimesLb.text = [NSString stringWithFormat:(@"密码错误，还可以再输入%ld次"),showErrorTimes];
        }
        
        self.errorTimesLb.hidden = NO;
        if(isNumberPassword){
            [self banPsdViewWithTime:1];
            [self.numberPasswordView revertToTheOriginalStateWithClearTime:1];
        }
    }
}

- (void)_callCancelAccount{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dismiss];
        if (self.forgetPwdBlock != nil) self.forgetPwdBlock();
    });
    [QAModuleService logoutAction];
}

#pragma mark -- action
- (void)faceIDTap{
    if(self.networkAlerter){
        return;
    }
    __weak typeof (self) weakSelf = self;
    [MOLocalAuthentication localAuth:[MOLocalAuthentication deviceSupportAuthType] isUnlock:YES result:^(BOOL success, BOOL isAuthFail) {
        if(success){
            [weakSelf.view endEditing:YES];
            //密码一致
            [CoreArchive setInt:0 key:ERROR_TIMES];
            if (MOLockType_Verify == weakSelf.type) {
                //禁用交互
                weakSelf.view.userInteractionEnabled = NO;
            }
            if (MOLockType_Verify == weakSelf.type) {
                if(weakSelf.successBlock != nil) weakSelf.successBlock(weakSelf,@"");
            }
        }else{
            if(isAuthFail){
                [weakSelf _authFailIsNumberPassword:weakSelf.psdStyle];
            }
        }
    }];
}

- (void)showCloseBarButtonItem {
    UIBarButtonItem *customBackButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_icon_back"] style:(UIBarButtonItemStylePlain) target:self action:@selector(dismiss)];
    customBackButton.tintColor = [UIColor main_Text_color];
    self.navigationItem.leftBarButtonItem = customBackButton;
    self.hidesBottomBarWhenPushed = YES;
}

- (void)showJumpBarButtonItem {
    _closeBtn = [[UIButton alloc] init];
    [_closeBtn setTitle:@"跳过" forState:(UIControlStateNormal)];
    [_closeBtn setTitleColor:[UIColor main_Text_color] forState:(UIControlStateNormal)];
    _closeBtn.titleLabel.font = WCIFontMedium(16);
    _closeBtn.size = CGSizeMake(44, 44);
    [_closeBtn sizeToFit];
    [_closeBtn addTarget:self action:@selector(dismissPass) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_closeBtn];
    // 隐藏tabbar
    self.hidesBottomBarWhenPushed = YES;
}

- (void)dismiss {
    if (self.closeBlock) {
        self.closeBlock();
    }
    [self dismiss:0];
}

- (void)dismissPass{
    [self dismiss];
}

#pragma mark -- layout
- (void)layoutUI{
    [self.view addSubview:self.topContainerView];
    [self.topContainerView addSubview:self.userHeaderShadowView];
    [self.topContainerView addSubview:self.userHeader];
    [self.topContainerView addSubview:self.nameLb];
    [self.topContainerView addSubview:self.lockInfoView];
    [self.view addSubview:self.passwordStyleButton];
    
    [self.view addSubview:self.numberPasswordView];
    [self.numberPasswordView addSubview:self.useGestureBtn];
    
    [self.view addSubview:self.lockView];
    [self.view addSubview:self.faceIDImgV];
    [self.view addSubview:self.touchIDImgV];
    [self.view addSubview:self.errorTimesLb];
    
    [_topContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(140);
        make.left.right.offset(0);
        make.top.offset(WCI_IPHONE_NAVIGATIONBAR_HEIGHT);
    }];
    
    [_userHeaderShadowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_userHeader).insets(UIEdgeInsetsMake(-1.5, -1.5, -1.5, -1.5));
    }];
    
    [_userHeader mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(72);
        make.centerX.centerY.offset(0);
//        make.top.equalTo(_lockInfoView);
    }];
    
    [_nameLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_userHeader.mas_bottom).offset(4);
        make.left.offset(16);
        make.right.offset(-16);
    }];
    
    [_lockInfoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(self.topContainerView);
        make.width.height.mas_equalTo(50);
    }];
    
    [_passwordStyleButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(30);
        make.right.offset(-30);
        make.height.mas_equalTo(44);
        make.bottom.offset(-WCI_IPHONE_SAFEBOTTOMAREA_HEIGHT-6);
    }];
    
    [_numberPasswordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [_useGestureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(30);
        make.right.offset(-30);
        make.height.mas_equalTo(44);
        make.bottom.offset(-40);
    }];
    
    [_faceIDImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(32);
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.topContainerView.mas_bottom).offset(25);
    }];
    
    [_touchIDImgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(40);
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.lockView.mas_bottom).offset(WCI_ScaleWidth(20));
    }];
    
    [_errorTimesLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(_faceIDImgV.mas_bottom).offset(14);
    }];
    
    [_lockView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(WCI_ScaleWidth(40));
        make.right.offset(-WCI_ScaleWidth(40));
        make.top.equalTo(_topContainerView.mas_bottom).offset(WCI_ScaleWidth(65));
        make.height.equalTo(_lockView.mas_width).multipliedBy(1.0);
    }];

}

- (UIWindow *)lockWindow {
    if (!_lockWindow) {
        _lockWindow = [[UIWindow alloc] initWithFrame:(UIScreen.mainScreen.bounds)];
        _lockWindow.windowLevel = UIWindowLevelStatusBar - 2.f;
        #if defined(__IPHONE_13_0) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0)
            if (@available(iOS 13.0, *)) {
                for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes){
                    if (windowScene.activationState == UISceneActivationStateForegroundActive){
                        _lockWindow.windowScene = windowScene;
                        break;
                    }
                }
            }
        #endif
    }
    return _lockWindow;
}


- (UILabel *)titleText{
    if (_titleText == nil) {
        _titleText = [[UILabel alloc] initWithFrame: CGRectMake(0, 0, 120, 40)];
        _titleText.backgroundColor = [UIColor clearColor];
        _titleText.textColor = [UIColor main_Text_color];
        _titleText.textAlignment = NSTextAlignmentCenter;
        [_titleText setFont:[UIFont boldSystemFontOfSize:17]];
        [_titleText setText:@""];
        self.navigationItem.titleView = _titleText;
    }
    return _titleText;
}

- (UIView *)topContainerView{
    if (!_topContainerView) {
        _topContainerView = [UIView new];
    }
    return _topContainerView;
}
- (UIImageView *)userHeader{
    if(!_userHeader){
        _userHeader = [UIImageView new];
        ViewRadius(_userHeader, 8);
    }
    return _userHeader;
}

- (UIView *)userHeaderShadowView {
    if (!_userHeaderShadowView) {
        UIView *shadowView = [[UIView alloc] init];
        shadowView.layer.shadowRadius = 14;
        shadowView.layer.shadowColor = [UIColor colorWithHexString:@"#0C101B" alpha:0.14].CGColor;
        shadowView.layer.shadowOffset = CGSizeMake(0, 7);
        shadowView.layer.shadowOpacity = 1.0;
        shadowView.layer.borderWidth = 1.5;
        shadowView.layer.borderColor = [UIColor whiteColor].CGColor;
        shadowView.layer.cornerRadius = 8;
        _userHeaderShadowView = shadowView;
    }
    return _userHeaderShadowView;
}

- (CLLockLabel *)nameLb{
    if (!_nameLb) {
        _nameLb = [CLLockLabel new];
        _nameLb.textAlignment = NSTextAlignmentCenter;
        _nameLb.textColor = [UIColor main_Text_color];
        _nameLb.font = WCIFontRegular(14);
    }
    return _nameLb;
}

- (CLLockInfoView *)lockInfoView{
    if(!_lockInfoView){
        _lockInfoView = [CLLockInfoView new];
        _lockInfoView.hidden = YES;
        _lockInfoView.backgroundColor = [UIColor clearColor];
    }
    return _lockInfoView;
}

- (CLLockView *)lockView{
    if(!_lockView){
        _lockView = [CLLockView new];
        _lockView.hidden = YES;
//        _lockView.backgroundColor = [UIColor clearColor];
    }
    return _lockView;
}

- (UIImageView *)faceIDImgV{
    if(!_faceIDImgV){
        _faceIDImgV = [UIImageView new];
        _faceIDImgV.image = [UIImage imageNamed:@"icon_lock_face"];
        _faceIDImgV.hidden = YES;
        _faceIDImgV.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(faceIDTap)];
        [_faceIDImgV addGestureRecognizer:tap];
    }
    return _faceIDImgV;
}

- (UIImageView *)touchIDImgV{
    if(!_touchIDImgV){
        _touchIDImgV = [UIImageView new];
        _touchIDImgV.image = [UIImage imageNamed:@"icon_lock_touch"];
        _touchIDImgV.hidden = YES;
        _touchIDImgV.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(faceIDTap)];
        [_touchIDImgV addGestureRecognizer:tap];
    }
    return _touchIDImgV;
}

- (UILabel *)errorTimesLb{
    if (!_errorTimesLb) {
        _errorTimesLb = [UILabel new];
        _errorTimesLb.textColor = [UIColor assist_Warning_Color];
        _errorTimesLb.font = WCIFontRegular(14);
        _errorTimesLb.textAlignment = NSTextAlignmentCenter;
        _errorTimesLb.hidden = YES;
    }
    return _errorTimesLb;
}

- (MONumberPassword *)numberPasswordView{
    if(!_numberPasswordView){
        _numberPasswordView = [MONumberPassword new];
        _numberPasswordView.hidden = YES;
    }
    return _numberPasswordView;
}

- (UIButton *)passwordStyleButton{
    if(!_passwordStyleButton){
        _passwordStyleButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_passwordStyleButton setTitle:@"使用数字密码方式" forState:UIControlStateNormal];
        [_passwordStyleButton setTitleColor:[UIColor colorWithHexString:@"00BA95"] forState:UIControlStateNormal];
        [_passwordStyleButton.titleLabel setFont:WCIFontRegular(14)];
        _passwordStyleButton.hidden = YES;
        [_passwordStyleButton addTarget:self action:@selector(changePasswordStyleAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _passwordStyleButton;
}

- (UIButton *)useGestureBtn{
    if(!_useGestureBtn){
        _useGestureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_useGestureBtn setTitle:@"使用手势密码方式" forState:UIControlStateNormal];
        [_useGestureBtn setTitleColor:[UIColor colorWithHexString:@"00BA95"] forState:UIControlStateNormal];
        [_useGestureBtn.titleLabel setFont:WCIFontRegular(14)];
        _useGestureBtn.hidden = YES;
        [_useGestureBtn addTarget:self action:@selector(useGestureStyleAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _useGestureBtn;
}

- (UILabel *)firstSubLabel{
    if (!_firstSubLabel) {
        _firstSubLabel = [UILabel new];
        _firstSubLabel.textColor = [UIColor main_Text_color];
        _firstSubLabel.font = WCIFontMedium(16);
        _firstSubLabel.textAlignment = NSTextAlignmentCenter;
        [_firstSubLabel setText:@"设置应用锁，让你的账号更安全"];
        _firstSubLabel.lineBreakMode = 1;
        _firstSubLabel.numberOfLines = 2;
        _firstSubLabel.hidden = YES;
    }
    return _firstSubLabel;
}

/**
 *  手势密码事件
 */
- (void)gesturePasswordEvent {
    WeakSelf(ws);
  
    /** 开始输入：第一次 */
    self.lockView.setPWBeginBlock = ^() {
        [weakSelf.nameLb showNormalMsg:CoreLockPWDTitleFirst];
    };
    
    /** 开始输入：确认 */
    self.lockView.setPWConfirmlock = ^() {
        [weakSelf.nameLb showNormalMsg:CoreLockPWDTitleConfirm];
    };
    
    /** 密码长度不够 */
    self.lockView.setPWSErrorLengthTooShortBlock = ^(NSUInteger currentCount) {
        [weakSelf.nameLb showWarnMsg:[NSString stringWithFormat:(@"至少连接%@个点，请重新输入"),@(CoreLockMinItemCount)]];
    };
    
    /** 两次密码不一致 */
    self.lockView.setPWSErrorTwiceDiffBlock = ^(NSString *pwd1,NSString *pwdNow) {
        [weakSelf.nameLb showWarnMsg:CoreLockPWDDiffTitle];
    };
    
    /** 第一次输入密码：正确 */
    self.lockView.setPWFirstRightBlock = ^(NSString *pwd) {
        [weakSelf.nameLb showNormalMsg:CoreLockPWDTitleConfirm];
        weakSelf.modifyCurrentTitle = CoreLockPWDTitleConfirm;
        weakSelf.lockInfoView.itemViewsM = [weakSelf.lockView.itemViewsM mutableCopy];
        weakSelf.passwordStyleButton.hidden = YES;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.lockInfoView setNeedsDisplay];
        });
    };
    
    /** 新旧密码一致 */
    self.lockView.verifyTwicePwdBlock = ^{
        [weakSelf.nameLb showWarnMsg:CoreLockModifyErrorTitle];
    };
    
    /** 再次输入密码一致 */
    self.lockView.setPWTwiceSameBlock = ^(NSString *pwd) {
        [weakSelf.nameLb showNormalMsg:CoreLockPWDTitleConfirm];
        weakSelf.lockInfoView.itemViewsM = [weakSelf.lockView.itemViewsM mutableCopy];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.lockInfoView setNeedsDisplay];
        });
        
        //存储密码
        [CoreArchive setStr:pwd key:WCICache.user.userId];
        //禁用交互
        weakSelf.view.userInteractionEnabled = NO;
        
        if (weakSelf.type == MOLockType_Set || weakSelf.type == MOLockType_FirstSet) {
            WCIToast.showMsg(@"设置成功");
        }
        
        [CoreArchive setBool:weakSelf.psdStyle key:OPEN_PASSWORD_STYLE];
        
        if (MOLockType_Modify == weakSelf.type) {
            WCIToast.showMsg(@"更改成功");
            [weakSelf dismiss:.5f];
        } else {
            if (weakSelf.successBlock != nil) weakSelf.successBlock(weakSelf,pwd);
        }
    };
    
    /*
     *  验证密码
     */
    
    /** 开始 */
    self.lockView.verifyPWBeginBlock = ^() {
        weakSelf.errorTimesLb.hidden = YES;
        [weakSelf.nameLb showNormalMsg:weakSelf.isClosePsd ? CoreLockVerifyNormalCloseTitle : [NSString stringWithFormat:(@"欢迎您，%@!"),WCICache.user.nickName]];
    };
    
    /** 验证 */
    self.lockView.verifyPwdBlock = ^(NSString *pwd) {
        //取出本地密码
        NSString *pwdLocal = [CoreArchive strForKey:WCICache.user.userId];
        
        BOOL res = [pwdLocal isEqualToString:pwd];
        
        if (res) {
            [weakSelf.view endEditing:YES];
            //密码一致
            [CoreArchive setInt:0 key:ERROR_TIMES];
            if (MOLockType_Verify == weakSelf.type) {
                //禁用交互
                weakSelf.view.userInteractionEnabled = NO;
            } else if (MOLockType_Modify == weakSelf.type) {
                //修改密码
                weakSelf.lockInfoView.hidden = NO;
                [weakSelf.passwordStyleButton setTitleColor:CoreMainTextColor forState:UIControlStateNormal];
                [weakSelf.passwordStyleButton setTitle:@"使用数字密码方式" forState:UIControlStateNormal];
                [weakSelf.nameLb showNormalMsg:CoreLockPWDTitleFirst];
                weakSelf.modifyCurrentTitle = CoreLockPWDTitleFirst;
            }
            
            if (MOLockType_Verify == weakSelf.type) {
                if (weakSelf.isClosePsd) {
                     [weakSelf clearAboutPasswordLocalValue];
                }
                if(weakSelf.successBlock != nil) weakSelf.successBlock(weakSelf,pwd);
            }
        } else {
            //密码不一致
            [weakSelf _authFailIsNumberPassword:NO];
        }
        
        return res;
    };
    
    /*
     *  修改
     */
    
    /** 开始 */
    self.lockView.modifyPwdBlock =^(){
        weakSelf.errorTimesLb.hidden = YES;
        [weakSelf.nameLb showNormalMsg:weakSelf.modifyCurrentTitle];
    };
}

/**
 *  数字密码事件
 */
- (void)numberPasswordEvent {
    WeakSelf(ws);
    /**
     *  密码开始输入
     */
    self.numberPasswordView.callBackStartInput = ^{
        if (![QAStringTool isBlankString:weakSelf.beforeErrorText]) {
            [weakSelf.numberPasswordView tipEditWithContent:weakSelf.beforeErrorText isError:NO];
        }
    };
    
    /*
     *  第一次输入数字密码(设置与修改密码共同使用)
     */
    self.numberPasswordView.callBackFirstInputPassword = ^{
        [weakSelf banPsdViewWithTime:1];
        weakSelf.beforeErrorText = CoreLockNumberPWDTitleConfirm;
        [weakSelf.numberPasswordView tipEditWithContent:CoreLockNumberPWDTitleConfirm isError:NO];
        weakSelf.useGestureBtn.hidden = YES;
    };
    
    /*
     *  两次密码输入相同(设置与修改密码共同使用)
     */
    self.numberPasswordView.callBackTwicePasswordSame = ^(NSString * _Nonnull psd) {
        [weakSelf.view endEditing:YES];
        //存储密码
        [CoreArchive setStr:psd key:WCICache.user.userId];
        
        [weakSelf.numberPasswordView tipEditWithContent:CoreLockNumberPWDTitleConfirm isError:NO];
        [weakSelf banPsdViewWithTime:0];

        if (weakSelf.type == MOLockType_Set || weakSelf.type == MOLockType_FirstSet) {
            WCIToast.showMsg(@"设置成功");
        } else if (weakSelf.type == MOLockType_Modify) {
            WCIToast.showMsg(@"更改成功");
        }
        
        [CoreArchive setBool:weakSelf.psdStyle key:OPEN_PASSWORD_STYLE];
        if(weakSelf.successBlock != nil) weakSelf.successBlock(weakSelf,psd);
    };
    
    /*
     *  两次密码输入不同(设置与修改密码共同使用)
     */
    self.numberPasswordView.callBackTwicePasswordDifferent = ^{
        [weakSelf banPsdViewWithTime:1];
        [weakSelf.numberPasswordView tipEditWithContent:CoreLockNumberPWDDiffTitle isError:YES];
    };
    
    /*
     *  新旧密码输入相同(修改密码时使用)
     */
    self.numberPasswordView.callBackSamePasswordAboutNewAndLocal = ^{
        [weakSelf banPsdViewWithTime:1];
        [weakSelf.numberPasswordView tipEditWithContent:CoreLockNumberModifyErrorTitle isError:YES];
    };
    
    /*
     *  验证密码正确（验证与修改密码共同使用）
     */
    self.numberPasswordView.callBackVerifyPasswordSuccess = ^(NSString * _Nonnull psd) {
        [weakSelf banPsdViewWithTime:1];
        [CoreArchive setInt:0 key:ERROR_TIMES];
        if (weakSelf.type == MOLockType_Verify) {
            [weakSelf.view endEditing:YES];
            if (weakSelf.isClosePsd) {
                [weakSelf clearAboutPasswordLocalValue];
            }
            
            if(weakSelf.successBlock != nil) weakSelf.successBlock(weakSelf,psd);
        } else {
            weakSelf.beforeErrorText = CoreLockNumberPWDTitleFirst;
            [weakSelf.numberPasswordView tipEditWithContent:CoreLockNumberPWDTitleFirst isError:NO];
            weakSelf.useGestureBtn.hidden = NO;
            [weakSelf.useGestureBtn setTitleColor:CoreMainTextColor forState:UIControlStateNormal];
             [weakSelf.passwordStyleButton setTitleColor:CoreMainTextColor forState:UIControlStateNormal];
            [weakSelf.useGestureBtn setTitle:@"使用手势密码方式" forState:UIControlStateNormal];
            [weakSelf.passwordStyleButton setTitle:@"使用数字密码方式" forState:UIControlStateNormal];
        }
    };
    
    /*
     *  验证密码错误（验证与修改密码共同使用）
     */
    self.numberPasswordView.callBackVerifyPasswordFalied = ^{
        [weakSelf _authFailIsNumberPassword:YES];
    };
    
    self.numberPasswordView.callBackTouchIDClicked = ^{
        [weakSelf faceIDTap];
    };
}

- (void)setType:(MOLockType)type {
    _type = type;
    //根据type自动调整label文字
    [self labelWithType];
}

/**
 *  根据type自动调整label文字
 */
- (void)labelWithType {
    
    if (MOLockType_Set == _type || _type == MOLockType_FirstSet) {
        //设置密码
        _psdStyle = NO;
        self.msg = _psdStyle ? CoreLockNumberPWDTitleFirst : CoreLockPWDTitleFirst;
        self.fd_prefersNavigationBarHidden = NO;
    } else if (MOLockType_Verify == _type) {
        _psdStyle = [CoreArchive boolForKey:OPEN_PASSWORD_STYLE];
        //验证密码
        self.msg = _psdStyle ? (_isClosePsd ? CoreLockNumberModifyNormalTitle : [NSString stringWithFormat:(@"欢迎您，%@!"),WCICache.user.nickName]) : (_isClosePsd ? CoreLockModifyNormalTitle : [NSString stringWithFormat:(@"欢迎您，%@!"),WCICache.user.nickName]);
        if (_isClosePsd) {
            self.fd_prefersNavigationBarHidden = NO;
        } else {
            self.fd_prefersNavigationBarHidden = YES;
        }
    } else if (MOLockType_Modify == _type) {
        _psdStyle = [CoreArchive boolForKey:OPEN_PASSWORD_STYLE];
        //修改密码
        self.msg = _psdStyle ? CoreLockNumberModifyNormalTitle : CoreLockModifyNormalTitle;
        self.fd_prefersNavigationBarHidden = NO;
    }
    
    self.beforeErrorText = self.msg;
}

/**
 *  消失
 */
- (void)dismiss:(NSTimeInterval)interval {
    _isLocking = NO;
    if (_lockWindow) {
        [UIView animateWithDuration:self.hideDismissAnimated ? 0 : 0.25 animations:^{
            self->_lockWindow.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
        } completion:^(BOOL finished) {
            self->_lockWindow.hidden = YES;
//            [self->_lockWindow removeFromSuperview];
            self->_lockWindow = nil;
        }];
        [NSNotificationCenter.defaultCenter postNotificationName:@"MONotification_LockVcDidDismiss" object:nil];
        return;
    }
    if (self.hideDismissAnimated) interval = 0;
     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(interval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         NSArray *viewcontrollers = self.navigationController.viewControllers;
         
         if (viewcontrollers.count > 1) {
             if ([viewcontrollers objectAtIndex:viewcontrollers.count - 1] == self) {
                 //push方式
                 [self.navigationController popViewControllerAnimated:self.hideDismissAnimated ? NO : YES];
             }
         } else {
             //present方式
            
             [self.presentingViewController dismissViewControllerAnimated:self.hideDismissAnimated ? NO : YES completion:^{
                 [NSNotificationCenter.defaultCenter postNotificationName:@"MONotification_LockVcDidDismiss" object:nil];
             }];
             [QATool.isBusy ? self : self.presentingViewController dismissViewControllerAnimated:self.hideDismissAnimated ? NO : YES completion:^{
                  [NSNotificationCenter.defaultCenter postNotificationName:@"MONotification_LockVcDidDismiss" object:nil];
             }];
         }
    });
}

/**
 *  禁止数字密码控件接受用户点击，1秒后恢复
 */
- (void)banPsdViewWithTime:(CGFloat)time {
    self.numberPasswordView.userInteractionEnabled = NO;
    WeakSelf(ws);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        weakSelf.numberPasswordView.userInteractionEnabled = YES;
    });
    
    [weakSelf.numberPasswordView revertToTheOriginalStateWithClearTime:time - 0.1];
}
#pragma mark - Class Methods

/**
 *  是否有本地密码缓存？即用户是否设置过初始密码？
 */
+ (BOOL)hasPwd {
    NSString *pwd = [CoreArchive strForKey:WCICache.user.userId];
    return pwd != nil && [MPLockHelper hasOpenGesturesPassowrd];
}

/**
 *  展示设置密码控制器
 */
+ (instancetype)showSettingLockVCInVC:(UIViewController *)vc successBlock:(void(^)(MOLockViewController *lockVC,NSString *pwd))successBlock{
    MOLockViewController *lockVC = [self lockVC:vc isPresent:NO];
    lockVC.titleText.text = @"设置密码";
    //设置类型
    lockVC.type = MOLockType_Set;
    //保存block
    lockVC.successBlock = successBlock;
    
    return lockVC;
}

///注册首次设置密码
+ (instancetype)showFirstSettingLockVCInVC:(UIViewController *)vc successBlock:(void(^)(MOLockViewController *lockVC,NSString *pwd))successBlock closeBlock:(void(^)(void))closeBlock {
    _isLocking = YES;
    MOLockViewController *lockVC = [[MOLockViewController alloc] init];
    lockVC.vc = vc;
    [[QATool getKeyWindow] endEditing:YES];
    [vc.navigationController pushViewController:lockVC animated:YES];
    
    lockVC.titleText.text = @"设置应用锁";
    //设置类型
    lockVC.type = MOLockType_FirstSet;
    //保存block
    lockVC.successBlock = successBlock;
    lockVC.closeBlock = closeBlock;
    return lockVC;
}

/**
 *  展示验证密码输入框
 *  @param isClose 是否关闭密码
 *  @param isPresent 是否present形式展示
 */
+ (instancetype)showVerifyLockVCInVC:(UIViewController *)vc isClose:(BOOL)isClose isPresent:(BOOL)isPresent forgetPwdBlock:(void(^)())forgetPwdBlock successBlock:(void(^)(MOLockViewController *lockVC, NSString *pwd))successBlock {
    
    MOLockViewController *lockVC = [self lockVC:vc isPresent:isPresent];
    if (isClose) {
        lockVC.titleText.text = @"关闭密码";
    } else {
        [NSNotificationCenter.defaultCenter postNotificationName:@"MONotification_ShowLockVc" object:nil];
    }
    //设置类型
    lockVC.isClosePsd = isClose;
    lockVC.type = MOLockType_Verify;
    //保存block
    lockVC.successBlock = successBlock;
    lockVC.forgetPwdBlock = forgetPwdBlock;
     
    return lockVC;
}

/**
 *  展示验证密码输入框
 */
+ (instancetype)showModifyLockVCInVC:(UIViewController *)vc forgetPwdBlock:(void(^)())forgetPwdBlock successBlock:(void(^)(MOLockViewController *lockVC, NSString *pwd))successBlock {
    
    MOLockViewController *lockVC = [self lockVC:vc isPresent:NO];
    lockVC.titleText.text = @"更改应用锁密码";
    //设置类型
    lockVC.type = MOLockType_Modify;
    //记录
    lockVC.successBlock = successBlock;
    lockVC.forgetPwdBlock = forgetPwdBlock;
    
    return lockVC;
}


+ (instancetype)lockVC:(UIViewController *)vc isPresent:(BOOL)isPresent {
    _isLocking = YES;
    MOLockViewController *lockVC = [[MOLockViewController alloc] init];
    lockVC.vc = vc;
    
    UIWindow *window = [QATool getKeyWindow];
    for (UIWindow *win in UIApplication.sharedApplication.windows) {
        if (win.tag == 6666) {
            window = (UIWindow *)win.superview;
            break;;
        }
    }
    
    [window endEditing:YES];
    if ([vc isKindOfClass:NSClassFromString(@"QASafeSettingVC")] && !isPresent) {
        [vc.navigationController pushViewController:lockVC animated:YES];
    } else {
        
        QABaseNavigationController *navVC = [[QABaseNavigationController alloc] initWithRootViewController:lockVC];
        navVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
        if (QATool.isBusy) {
            lockVC.lockWindow.rootViewController = navVC;
            lockVC.lockWindow.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
            lockVC.lockWindow.hidden = NO;
            //            [window addSubview:lockVC.lockWindow];
            [UIView animateWithDuration:0.25 animations:^{
                lockVC.lockWindow.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
            } completion:^(BOOL finished) {
                
            }];
            return lockVC;
        } else {
            [vc presentViewController:navVC animated:YES completion:nil];
        }
    }
    return lockVC;
}

- (void)changePasswordStyleAction:(UIButton *)sender{
    self.firstSubLabel.hidden = 1;
    //手势密码时，下方蓝色按钮的点击事件
    if ([sender.titleLabel.text mw_isEqualToString:@"忘记应用锁密码"]) {
         WeakSelf(ws);
        [MOAlerter alertWithTitle:@"提示" message:@"请重新登录并到安全中心重新\n设置应用锁" leftTitle:@"取消" leftAction:nil rightTitle:@"重新登录" rightAction:^(MOAlerter *alerter) {
            [weakSelf dismiss];
            if (weakSelf.forgetPwdBlock != nil) weakSelf.forgetPwdBlock();
        } touchHide:NO superView:self.alertSuperView];
    }else if ([sender.titleLabel.text mw_isEqualToString:@"使用数字密码方式"]) {
        sender.hidden = YES;
        self.numberPasswordView.backgroundColor = [UIColor colorWithLightColorStr:@"FFFFFF" DarkColor:@"131C26"];
        _numberPasswordView.hidden = NO;
        _useGestureBtn.hidden = NO;
        _lockView.hidden = YES;
        _lockInfoView.hidden = YES;
        if (_type == MOLockType_Verify) {
            [self.numberPasswordView tipEditWithContent:CoreLockNumberVerifyNormalTitle isError:NO];
            self.beforeErrorText = CoreLockNumberVerifyNormalTitle;
        } else {
            [self.numberPasswordView tipEditWithContent:CoreLockNumberPWDTitleFirst isError:NO];
            self.beforeErrorText = CoreLockNumberPWDTitleFirst;
        }
        
        if (_type == MOLockType_Modify) {
            [self.useGestureBtn setTitleColor:CoreMainTextColor forState:UIControlStateNormal];
            [self.useGestureBtn setTitle:@"使用手势密码方式" forState:UIControlStateNormal];
            _type = MOLockType_Set;
            self.numberPasswordView.type = _type;
        }
        //数字密码为YES
        _psdStyle = YES;
    }
}

- (void)useGestureStyleAction:(UIButton *)sender{
    self.firstSubLabel.hidden = 0;
    //数字密码时，下方蓝色按钮的点击事件
    if ([sender.titleLabel.text mw_isEqualToString:@"忘记应用锁密码"]) {
        [self.view endEditing:YES];
        WeakSelf(ws);
        [MOAlerter alertWithTitle:@"提示" message:@"请重新登录并到安全中心重新\n设置应用锁" leftTitle:@"取消" leftAction:nil rightTitle:@"重新登录" rightAction:^(MOAlerter *alerter) {
            [weakSelf dismiss];
            if (weakSelf.forgetPwdBlock != nil) weakSelf.forgetPwdBlock();
        } touchHide:NO superView:self.alertSuperView];
    } else if ([sender.titleLabel.text mw_isEqualToString:@"使用手势密码方式"]) {
        //使用手势密码
        sender.hidden = YES;
        _numberPasswordView.hidden = YES;
        [_numberPasswordView revertToTheOriginalStateWithClearTime:0];
        _passwordStyleButton.hidden = NO;
        _lockView.hidden = NO;
        _lockInfoView.hidden = NO;
        
        if (_type == MOLockType_Modify) {
            _type = MOLockType_Set;
            self.lockView.type = _type;
        }
        
        if (_type == MOLockType_Verify) {
            [self.nameLb showNormalMsg:CoreLockVerifyNormalTitle];
        } else if (_type == MOLockType_Modify) {
            [self.nameLb showNormalMsg:CoreLockModifyNormalTitle];
        } else {
            [self.nameLb showNormalMsg:CoreLockPWDTitleFirst];
        }
        //手势密码为NO
        _psdStyle = NO;
    }
}

- (void)clearAboutPasswordLocalValue {
    [MPLockHelper clearAboutPasswordLocalValue];
}
/**
 *  清除登录成功后保存的数据
 */
- (void)clearLoginSuccessData {
    [QAModuleService logoutAction];
}

/// 是否处于锁屏
+ (BOOL)isLocking {
    return _isLocking;
}


- (UIView *)alertSuperView {
    return (_lockWindow && !_lockWindow.hidden) ? _lockWindow : nil;
}

#pragma mark - 日志描述
- (NSString *)displayLogString {
    return [NSString stringWithFormat:@"LockVc:%@ \n isLocking:%d \n LockWindow:%@", self, _isLocking, _lockWindow];
}
@end
